package com.zygh.policeasset.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.zygh.policeasset.component.CommonResult;
import com.zygh.policeasset.component.DataLabelsComponent;
import com.zygh.policeasset.mapper.AssetsNoMapper;
import com.zygh.policeasset.pojo.Images;
import com.zygh.policeasset.pojo.Purchase;
import com.zygh.policeasset.pojo.ZipOrRar;
import com.zygh.policeasset.service.AssetsFilesService;
import com.zygh.policeasset.service.ImagesService;
import com.zygh.policeasset.service.PurchaseService;
import com.zygh.policeasset.utils.MapUtil;
import com.zygh.policeasset.utils.UnZipAndRarUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.File;
import java.io.FileInputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.validation.ConstraintViolationException;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RequestMapping({"/purchaseFiles"})
@Api(tags = {"采购资产模块上传数据压缩包"})
@RestController
/* loaded from: police-asset-2.0-0.0.1-SNAPSHOT.jar:BOOT-INF/classes/com/zygh/policeasset/controller/PurchaseFilesController.class */
public class PurchaseFilesController {
    @Autowired
    PurchaseService purchaseService;
    @Autowired
    ImagesService imagesService;
    @Value("${file.uploadFoldercg}")
    private String uploadFoldercg;
    @Autowired
    AssetsNoMapper assetsNoMapper;
    @Autowired
    AssetsFilesService assetsFilesService;

    @RequestMapping(value = {"/addRepository"}, method = {RequestMethod.POST})
    @Transactional(rollbackFor = {Exception.class})
    @ApiOperation("上传采购数据压缩包")
    public Object addRepository(@RequestBody List<MultipartFile> files, @RequestParam(value = "projectNo", required = false) String projectNo, @RequestParam(value = "inputNum", required = false) String inputNum, @RequestParam(value = "selfBuilt", required = false) Integer selfBuilt) {
        try {
            if (!files.isEmpty() && files.size() > 0) {
                for (MultipartFile multipartFile : files) {
                    String outDir = this.uploadFoldercg + System.currentTimeMillis() + "/";
                    File outFile = new File(outDir);
                    if (!outFile.exists()) {
                        outFile.mkdirs();
                    }
                    String fileName = multipartFile.getOriginalFilename();
                    String filePath = outDir + fileName;
                    multipartFile.transferTo(new File(filePath));
                    if (!fileName.substring(fileName.lastIndexOf(".")).equals(".zip")) {
                        return new CommonResult().validateFailed("上传文件类型错误,只允许上传zip类型的压缩包");
                    }
                    this.assetsFilesService.deCgCompress(UnZipAndRarUtil.unZip(filePath, outDir), projectNo, inputNum, "cg", selfBuilt);
                    UnZipAndRarUtil.delete(new File(outDir));
                }
            }
            return new CommonResult().success();
        } catch (ExcelAnalysisException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new CommonResult().validateFailed(e.getCause().getMessage());
        } catch (ConstraintViolationException e2) {
            e2.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new CommonResult().validateFailed(e2.getMessage());
        } catch (Exception e3) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e3.printStackTrace();
            return new CommonResult().validateFailed(e3.getMessage());
        }
    }

    public String deCompress(ZipOrRar zipOrRar, String[] columns, String projectNo, String inputNum) throws Exception {
        Hyperlink link;
        String outPath = zipOrRar.getFilePath();
        zipOrRar.getRelativePaths();
        Sheet sheet = UnZipAndRarUtil.readExcel(outPath + zipOrRar.getExcelName());
        int lastRowNum = sheet.getLastRowNum();
        int lastCellNum = columns.length;
        Map<String, String> map = new LinkedHashMap<>();
        Purchase purchase = new Purchase();
        int resutlNum = 0;
        for (int rowNum = 1; rowNum <= lastRowNum; rowNum++) {
            Row row = sheet.getRow(rowNum);
            for (int cellNum = 0; cellNum < lastCellNum; cellNum++) {
                Cell cell = row.getCell(cellNum);
                String cellData = UnZipAndRarUtil.getStringValue(cell);
                if (cell == null || (link = cell.getHyperlink()) == null) {
                    map.put(columns[cellNum], cellData);
                } else {
                    map.put(columns[cellNum], link.getAddress());
                }
            }
            try {
                MapUtil.mapToBean(map, purchase);
                String images = purchase.getImages();
                purchase.setProjectNo(projectNo);
                purchase.setMoney(purchase.getMoney().replace(",", ""));
                purchase.setInputNum(Integer.valueOf(inputNum));
                purchase.setImages(outPath + images);
                purchase.setDataLabelsId(DataLabelsComponent.toEnableId);
                purchase.setStatusNum("1");
                if (this.purchaseService.add1(purchase, "1").intValue() > 0) {
                    resutlNum++;
                }
                if (!"".equals(images) && images != null) {
                    Images images1 = new Images();
                    images1.setProjectNo(projectNo);
                    images1.setProjectName(projectNo);
                    images1.setType("cg");
                    images1.setAssetsId(purchase.getId().intValue());
                    images1.setIcon(createFileItem(purchase.getImages()));
                    String imagesPath = this.imagesService.storeFile(images1);
                    images1.setCreateDate(DateUtil.now());
                    images1.setConnect(imagesPath);
                    this.imagesService.add(images1);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return e.toString();
            }
        }
        if (lastRowNum == resutlNum) {
            return "上传成功";
        }
        return "上传失败";
    }

    public MultipartFile createFileItem(String filePath) {
        FileInputStream inputStream = null;
        try {
            MultipartFile multipartFile = null;
            inputStream = null;
            try {
                File pdfFile = new File(filePath);
                inputStream = new FileInputStream(pdfFile);
                multipartFile = new MockMultipartFile("file", pdfFile.getName(), "text/plain", IOUtils.toByteArray(inputStream));
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e2) {
                e2.printStackTrace();
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (Exception e3) {
                        e3.printStackTrace();
                    }
                }
            }
            return multipartFile;
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e4) {
                    e4.printStackTrace();
                    throw th;
                }
            }
            throw th;
        }
    }
}